<script setup lang="ts">
import JinDrawer from "@/components/framework/jin-drawer/jin-drawer.vue";
import { menuList } from "@/services/menuApi.ts";
import { reactive, ref } from "vue";
import type { MenuListResType } from "@/types/MenuType.ts";
import {
  rolePermissionApi,
  rolePermissionListApi,
} from "@/services/roleApi.ts";
import { Message } from "@arco-design/web-vue";

const drawer = ref<{
  init: () => void;
  close: () => void;
}>();

const options = reactive({
  id: "",
});

const checkedKeys = ref<string[]>([]);

const loading = ref(false);

const treeData = ref<MenuListResType[]>([]);

const emits = defineEmits<{
  (e: "list"): void;
}>();

function queryData() {
  menuList({
    name: "",
  })
    .then((res) => {
      if (res.code === 200) {
        treeData.value = res.data;
      }
    })
    .finally(() => {
      rolePermissionListApi({
        id: options.id,
      }).then((res) => {
        if (res.code === 200) {
          checkedKeys.value = res.data;
        }
      });
    });
}

const init = (id: string) => {
  drawer.value?.init();
  options.id = id;
  loading.value = false;
  queryData();
};

const handleCancel = () => {
  drawer.value?.close();
};

const handleOk = () => {
  if (checkedKeys.value.length === 0) {
    handleCancel();
    return;
  }
  loading.value = true;
  rolePermissionApi({
    roleId: options.id,
    permissionIds: checkedKeys.value,
  }).then((res) => {
    if (res.code === 200) {
      Message.success(res.data);
      handleCancel();
      emits("list");
    }
  });
};

defineExpose({
  init,
});

function traverseChildren(node) {
  if (node.children && node.children.length > 0) {
    return node.children.reduce((acc, child) => {
      const childIds = traverseChildren(child);
      return [...acc, ...childIds];
    }, []);
  } else {
    return [node.id];
  }
}

const onCheck = (checkedKeysValue, data) => {

  const childrenMore = traverseChildren(data.node);
  const childrenIds = data.node.children.map((child) => child.id);
  if (data.node.children && data.node.children.length > 0) {
    if (data.checked) {
      // 父节点选中，选中子节点
      checkedKeys.value = Array.from(
          new Set([...checkedKeys.value, ...childrenMore]) //集合
      );
      checkedKeys.value = Array.from(
          new Set([...checkedKeys.value, ...childrenIds]) //集合
      );
    } else {
      // 父节点取消选中，取消子节点
      checkedKeys.value = checkedKeys.value.filter(
          (key) => !childrenMore.includes(key)
      );
      checkedKeys.value = checkedKeys.value.filter(
          (key) => !childrenIds.includes(key)
      );
    }
  } else {
    if (data.checked) {
      checkedKeys.value = Array.from(
          new Set([...checkedKeys.value, ...childrenIds]) //集合
      );
    } else {
      checkedKeys.value = checkedKeys.value.filter(
          (key) => !childrenIds.includes(key)
      );
    }
  }
};

const menuTreeFieldNames = {
  key: "id",
  title: "name",
  children: "children",
  icon: "",
};

</script>

<template>
  <jin-drawer
    title="角色权限配置"
    :is-before-ok="false"
    ref="drawer"
    @ok="handleOk"
    @cancel="handleCancel"
    :loading="loading"
  >
    <a-tree
        :checkable="true"
        v-model:checked-keys="checkedKeys"
        @check="onCheck"
        :data="treeData"
        :fieldNames="menuTreeFieldNames"
        :check-strictly="true"
    ></a-tree>
<!--    <a-checkbox-group direction="vertical" v-model="checkedKeys" @change="handleChange">
      <a-space  direction="vertical">
        <div class="menu" v-for="item in treeData" :key="item.id">
          <a-checkbox :value="item.id">{{ item.name }}</a-checkbox>
          <div v-if="item.children && item.children.length > 0" class="route">
            <a-space  direction="vertical">
              <div v-for="r in item.children" :key="r.id">
                <a-checkbox :value="r.id">{{ r.name }}</a-checkbox>
                <div class="route" v-if="r.children && r.children.length > 0">
                  <a-checkbox v-for="b in r.children" :key="b.id" :value="b.id">{{ b.name }}</a-checkbox>
                </div>
              </div>
            </a-space>
          </div>
        </div>
      </a-space>
    </a-checkbox-group>-->
  </jin-drawer>
</template>

<style scoped lang="scss">
.route {
  margin-left: 2em;
}
</style>
